package com.boyinet.activation.util;

/**
 *
 */
public class CDKeyUtil {

    //机器版本号

    /**
     * 激活码生成方法
     *
     * @param mac          密钥类别（固定8位16进制数字）
     * @param softwareCode 软件代码 （固定4位16进制数字）
     * @param deadline     使用期限 枚举
     * @return 返回的激活码
     */
    public static String createCDkey(String mac, String softwareCode, Integer deadline) throws Exception {
        String aeSencrypt = CDKeyEncryptUtils.AESencrypt(mac + softwareCode + deadline);
        return confusion(aeSencrypt);
    }

    /**
     * 激活码混淆方法
     * 奇数位+偶数位
     *
     * @return 返回激活码混淆后的序列
     */
    public static String confusion(String CDKey) {
        String deCDKey;
        //1.获取奇数位字串
        StringBuilder odd = new StringBuilder();
        for (int i = 0; i < CDKey.length(); i = i + 2) {
            odd.append(CDKey.charAt(i));
        }
        //2.获取偶数位字串
        StringBuilder even = new StringBuilder();
        for (int i = 1; i < CDKey.length(); i = i + 2) {
            even.append(CDKey.charAt(i));
        }
        //3.拼接
        deCDKey = (odd.append(even)).toString();
        return deCDKey;
    }

    /**
     * 激活码解除混淆方法
     *
     * @return 返回激活码解除混淆后的序列
     */
    public static String deConfusion(String deCDKey) {
        StringBuilder CDKey = new StringBuilder();
        //1. 拆分
        int oddCount = (deCDKey.length() / 2) + (deCDKey.length() % 2);
        String odd = deCDKey.substring(0, oddCount);
        String even = deCDKey.substring(oddCount);
        //2. 复原激活码
        if (odd.length() == even.length()) {
            for (int i = 0; i < odd.length(); i++) {
                CDKey.append(odd.charAt(i)).append(even.charAt(i));
            }
        } else {
            for (int i = 0; i < even.length(); i++) {
                CDKey.append(odd.charAt(i)).append(even.charAt(i));
            }
            CDKey.append(odd.charAt(odd.length() - 1));
        }
        return CDKey.toString();
    }

    public static byte[] hexStringToBytes(String hex) {
        byte[] bytes = new byte[hex.length() / 2];

        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = Byte.parseByte(hex.substring(i * 2, (i * 2) + 2),16);
        }
        return bytes;
    }


    public static void main(String[] args) throws Exception {

        System.out.println(createCDkey("a4a4a4a4", "001", 0));
    }
}
